export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  // 配置信息 - 已经填好你的信息
  const FEISHU_APP_ID = "cli_a86c6ac6f478d013";
  const FEISHU_APP_SECRET = "cncPhnU5BMfKKWXJWCdhvdR8Pcx2Drb2";
  const FEISHU_APP_TOKEN = "S5L1bO9dsaKlArsrDMjcfkMXnAh";
  const FEISHU_LICENSES_TABLE_ID = "tbljohl3hkfNW8mc";

  // 生成13位随机授权码
  function generateLicenseKey() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 13; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }

  try {
    // 获取访问令牌
    const tokenResponse = await fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        app_id: FEISHU_APP_ID,
        app_secret: FEISHU_APP_SECRET,
      }),
    });

    const tokenData = await tokenResponse.json();
    
    if (tokenData.code !== 0) {
      return res.json({ success: false, message: '获取访问令牌失败' });
    }

    const ACCESS_TOKEN = tokenData.tenant_access_token;

    // 生成授权码
    const licenseKey = generateLicenseKey();

    // 添加到Licenses表
    const addLicenseUrl = `https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_APP_TOKEN}/tables/${FEISHU_LICENSES_TABLE_ID}/records`;
    
    const addResponse = await fetch(addLicenseUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        fields: {
          "license_key": licenseKey,
          "max_devices": 3,
          "devices_registered": 0,
          "is_active": true
        }
      }),
    });

    const result = await addResponse.json();

    if (result.code === 0) {
      res.json({ 
        success: true, 
        license_key: licenseKey,
        message: '授权码生成成功' 
      });
    } else {
      res.json({ 
        success: false, 
        message: '生成授权码失败：' + result.msg 
      });
    }

  } catch (error) {
    console.error('Generate error:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
}